package com.iqiyi.pps.epg.web.rpc;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.iqiyi.mams.hedvig.rpc.core.ServiceConfig;
import com.iqiyi.mams.hedvig.rpc.core.ServiceSchema;
import com.iqiyi.mams.hedvig.rpc.core.ServiceType;
import com.iqiyi.mams.hedvig.rpc.server.HedwigServer;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * User: rainliang
 * Mail: rainliang@qiyi.com
 * Date: 2014/7/11
 * Time: 0:10
 * Desc:
 */
public class HedWigRpcServer {

    private final Logger logger = LoggerFactory.getLogger(HedWigRpcServer.class);

    private static ServiceConfig config;
    private HedwigServer server;

    private List<HedWigRpcConfig> serverInfos;
    private boolean lockKey = false;

    public void init(){
        if (lockKey)
            return;
        logger.info("[HedWigRpcServer][init][start][serverInfos={}]",JSON.toJSON(serverInfos));
        try {
            if(CollectionUtils.isNotEmpty(this.getServerInfos())){

                if(server==null){
                    server=HedwigServer.getServer();
                }

                for (HedWigRpcConfig hedWigRpcConfig:this.getServerInfos()){
                    Class ifaceimplClass=Class.forName(Preconditions.checkNotNull(hedWigRpcConfig.getServiceImpl()));
                    Class<?>[] interfaces = ifaceimplClass.getInterfaces();
                    Class<?> innerClass = interfaces[0];

                    config = ServiceConfig.newBuilder()
                            .type(ServiceType.THRIFT)
                            .schema(ServiceSchema.TCP)
                            .serviceFace(innerClass)
                            .serviceImpl(ifaceimplClass)
                            .port(hedWigRpcConfig.getPort())
                            .build();

                    server.registerService(config);
                    logger.info("[HedWigRpcServer][hedWigRpcConfig registered finished][serverInfos={}]",JSON.toJSON(hedWigRpcConfig));

                }
                server.start();
                logger.info("[HedWigRpcServer][init][finished][serverInfos={}]",JSON.toJSON(serverInfos));
            }
        } catch (ClassNotFoundException e) {
            logger.error("[HedWigRpcServer][init][error]", e);
        } catch (Exception e) {
            logger.error("[HedWigRpcServer][init][error]", e);
        }
    }

    public List<HedWigRpcConfig> getServerInfos() {
        return serverInfos;
    }

    public void setServerInfos(List<HedWigRpcConfig> serverInfos) {
        this.serverInfos = serverInfos;
    }

    public void setLockKey(boolean lockKey) {
        this.lockKey = lockKey;
    }
}
